package com.ktwlrj.logmanage.util;

import com.ktwlrj.logmanage.entity.LogEntity;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 日志阻塞队列
 *
 * @author zhouxuanhong
 * @date 2019-04-19 14:20
 * @since JDK1.8
 */
public class LogQueue {
    /**
     * 队列大小
     */
    public static final int QUEUE_MAX_SIZE = 500;
    /**
     * 阻塞队列
     */
    private static BlockingQueue<LogEntity> blockingQueue = null;

    static {
        /*
         *队列初始化
         */
        blockingQueue = new LinkedBlockingQueue<>(QUEUE_MAX_SIZE);
    }

    /**
     * 日志入阻塞队列
     *
     * @param logEntity ${@link LogEntity}  待入队列日志
     * @author zhouxuanhong
     * @date 2019-04-19 15:30
     */
    public static void push(LogEntity logEntity) throws Exception {
        //队列已满时,会阻塞队列,直到未满
        blockingQueue.put(logEntity);
    }

    /**
     * 日志出阻塞队列
     *
     * @return Log ${@link LogEntity}
     * @author zhouxuanhong
     * @date 2019-04-19 15:31
     */
    public static LogEntity poll() {
        LogEntity result = null;
        try {
            //队列为空时会阻塞队列,直到不是空
            result = blockingQueue.take();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 获取队列大小
     *
     * @author zhouxuanhong
     * @date 2019-04-19 15:31
     */
    public static int size() {
        return blockingQueue.size();
    }

}
